package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.VoCCY.*;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements CartService{

    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketSystemMapper marketSystemMapper;

    @Override
    public int selectCartById(Integer userId) {
        MarketCartExample example = new MarketCartExample();
        example.createCriteria().andUserIdEqualTo(userId);

        List<MarketCart> marketCarts = marketCartMapper.selectByExample(example);
        System.out.println(marketCarts);
        return marketCarts.size();
    }

    @Override
    public BaseRespVo insertCart(WxCartAddBo cartAddBo, Integer userId) {
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(cartAddBo.getGoodsId());
        String name = marketGoods.getName();
        String picUrl = marketGoods.getPicUrl();
        MarketGoodsProduct product = marketGoodsProductMapper.selectByPrimaryKey(cartAddBo.getProductId());
        BigDecimal price = product.getPrice();


        if (product.getNumber() < cartAddBo.getNumber()) {
            return BaseRespVo.invalidParameter("库存不足，请选择别的商品");
        }
        String[] specifications = product.getSpecifications();
        String goodsSn = String.valueOf(cartAddBo.getGoodsId());

        MarketCartExample example1 = new MarketCartExample();
        example1.createCriteria().andUserIdEqualTo(userId);
        List<MarketCart> marketCarts1 = marketCartMapper.selectByExample(example1);
        for (MarketCart marketCart : marketCarts1) {
            if (marketCart.getProductId() == cartAddBo.getProductId()) {
                Integer id = marketCart.getId();
                Short number = marketCart.getNumber();
                int num = number + cartAddBo.getNumber();
                MarketCart marketCart1 = new MarketCart();
                marketCart1.setId(id);
                marketCart1.setNumber((short) num);
                marketCart1.setPrice(marketCart.getPrice().add(marketCart.getPrice()));
                marketCartMapper.updateByPrimaryKeySelective(marketCart1);

                MarketCartExample example = new MarketCartExample();
                example.createCriteria().andUserIdEqualTo(userId);

                List<MarketCart> marketCarts = marketCartMapper.selectByExample(example);
                int number4 = 0;
                for (MarketCart cart : marketCarts) {
                    Short number1 = cart.getNumber();
                    number4 += number1;
                }
                return BaseRespVo.ok(number4);
            }
        }

        MarketCart marketCart = new MarketCart(null,userId,cartAddBo.getGoodsId(),
                goodsSn,name,cartAddBo.getProductId(),price,(short)cartAddBo.getNumber(),
                specifications,true,picUrl,new Date(),new Date(),false);

        marketCartMapper.insert(marketCart);

        MarketCartExample example = new MarketCartExample();
        example.createCriteria().andUserIdEqualTo(userId);

        List<MarketCart> marketCarts = marketCartMapper.selectByExample(example);
        int number2 = 0;
        for (MarketCart cart2 : marketCarts) {
            Short number3 = cart2.getNumber();
            number2 += number3;
        }
        return BaseRespVo.ok(number2);
    }

    @Override
    public WxCartIndexVo indexCart(Integer userId) {
        MarketCartExample example = new MarketCartExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(example);

        int goodsCount = marketCarts.size();
        int checkedGoodsCount = 0;
        double goodsAmount = 0;
        double checkedGoodsAmount = 0;

        for (MarketCart marketCart : marketCarts) {
            if (marketCart.getChecked()) {
                checkedGoodsCount++;
                checkedGoodsAmount = (new BigDecimal(Double.toString(goodsAmount)).add(marketCart.getPrice())).doubleValue();
            }
            goodsAmount = (new BigDecimal(Double.toString(goodsAmount)).add(marketCart.getPrice())).doubleValue();
        }


        WxCartIndexVoVo cartIndexVoVo = new WxCartIndexVoVo(goodsCount,checkedGoodsCount,goodsAmount,checkedGoodsAmount);

        WxCartIndexVo cartIndexVo = new WxCartIndexVo();
        cartIndexVo.setCartTotal(cartIndexVoVo);
        cartIndexVo.setCartList(marketCarts);

        return cartIndexVo;
    }

    @Override
    public BaseRespVo updateCart(WxCartAddBo cartAddBo, Integer userId) {
        MarketGoodsProduct product = marketGoodsProductMapper.selectByPrimaryKey(cartAddBo.getProductId());
        if (product.getNumber() < cartAddBo.getNumber()) {
            return BaseRespVo.invalidParameter("该规格的库存不足，暂时不支持修改哦");
        }

        MarketCartExample example = new MarketCartExample();
        example.createCriteria().andUserIdEqualTo(userId);

        MarketCart marketCart = new MarketCart();
        marketCart.setUpdateTime(new Date());
        marketCart.setNumber((short) cartAddBo.getNumber());
        marketCartMapper.updateByExampleSelective(marketCart,example);

        return BaseRespVo.ok3();
    }

    @Override
    public WxCartIndexVo updateChecked(WxCartCheckedBo cartCheckedBo,Integer userId) {

        MarketCartExample example2 = new MarketCartExample();
        MarketCartExample.Criteria criteria = example2.createCriteria();

        criteria.andUserIdEqualTo(userId);
        Integer[] productIds = cartCheckedBo.getProductIds();
        criteria.andProductIdIn(Arrays.asList(productIds));

        MarketCart marketCart2 = new MarketCart();
        if (cartCheckedBo.getIsChecked() == 1) {
            marketCart2.setChecked(true);
        } else if (cartCheckedBo.getIsChecked() == 0) {
            marketCart2.setChecked(false);
        }

        marketCartMapper.updateByExampleSelective(marketCart2,example2);

        return indexCart(userId);
    }

    @Override
    public BaseRespVo selectCart(Integer cartId, Integer addressId, Integer couponId, Integer userCouponId,Integer userId,Integer grouponRulesId) {

        if (addressId == 0 || userCouponId == 0) {
            return BaseRespVo.invalidParameter("请选择地址和要使用的优惠券");
        }

        // 运费     大于等于  keyValue2  不用给运费  keyValue
        MarketSystemExample marketSystemExample2 = new MarketSystemExample();
        MarketSystemExample.Criteria criteria5 = marketSystemExample2.createCriteria();
        criteria5.andKeyNameEqualTo("market_express_freight_min");
        List<MarketSystem> marketSystems2 = marketSystemMapper.selectByExample(marketSystemExample2);
        String keyValue2 = marketSystems2.get(0).getKeyValue();

        MarketSystemExample marketSystemExample = new MarketSystemExample();
        MarketSystemExample.Criteria criteria4 = marketSystemExample.createCriteria();
        criteria4.andKeyNameEqualTo("market_express_freight_value");
        List<MarketSystem> marketSystems = marketSystemMapper.selectByExample(marketSystemExample);
        String keyValue = marketSystems.get(0).getKeyValue();


        // 地址 list
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(addressId);

        // 购物车
        List<MarketCart> marketCarts = new ArrayList<>();
        MarketCart marketCart;
        BigDecimal price = new BigDecimal(0);

        if (cartId != 0) {
            marketCart = marketCartMapper.selectByPrimaryKey(cartId);
            Short number = marketCart.getNumber();
            Integer productId1 = marketCart.getProductId();

            MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId1);
            Integer number1 = marketGoodsProduct.getNumber();

            if (number > number1) {
                return BaseRespVo.invalidParameter("库存不足，实在抱歉哦");
            }
            Integer number2 = number1 - number;
            MarketGoodsProduct marketGoodsProduct1 = new MarketGoodsProduct();
            marketGoodsProduct1.setNumber(number2);
            marketGoodsProduct1.setId(productId1);

            //修改规格的数量
            marketGoodsProductMapper.updateByPrimaryKeySelective(marketGoodsProduct1);

            // 删除购物车
            marketCartMapper.deleteByPrimaryKey(cartId);

            marketCarts.add(marketCart);
            price = marketCart.getPrice();
        }

        if (cartId == 0) {
            // 说明不止一个商品 要根据勾选来下单
            MarketCartExample example = new MarketCartExample();
            MarketCartExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andCheckedEqualTo(true);

            List<MarketCart> marketCarts1 = marketCartMapper.selectByExample(example);
           marketCarts.addAll(0,marketCarts1);
            for (MarketCart cart : marketCarts1) {
                price = price.add(cart.getPrice());
                Short number = cart.getNumber();
                Integer productId = cart.getProductId();



                MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
                Integer number1 = marketGoodsProduct.getNumber();

                if (number > number1) {
                    return BaseRespVo.invalidParameter("库存不足，实在抱歉哦");
                }
                Integer number2 = number1 - number;
                MarketGoodsProduct marketGoodsProduct1 = new MarketGoodsProduct();
                marketGoodsProduct1.setNumber(number2);
                marketGoodsProduct1.setId(productId);

                //修改规格的数量
                marketGoodsProductMapper.updateByPrimaryKeySelective(marketGoodsProduct1);

                // 删除购物车
                marketCartMapper.deleteByPrimaryKey(cart.getId());
            }
        }

        WxCartCheckoutVo checkoutVo = new WxCartCheckoutVo();

        //使用优惠券
        if (userCouponId != -1 && couponId != -1) {

            if (couponId == 0) {
                MarketCouponUser marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(userCouponId);
                Integer couponId1 = marketCouponUser.getCouponId();
                couponId = couponId1;
            }


            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
            BigDecimal discount = marketCoupon.getDiscount(); // 满减 减
            BigDecimal min = marketCoupon.getMin(); // 满减 满

            if (price.doubleValue() < min.doubleValue()) {
                price = price.subtract(discount);
            }
            MarketCouponUser marketCouponUser1 = new MarketCouponUser();
            marketCouponUser1.setStatus((short) 2);
            marketCouponUser1.setId(userCouponId);

            marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser1);
            if (price.doubleValue() < Integer.parseInt(keyValue2)) {
                price = new BigDecimal(price.doubleValue() + Integer.parseInt(keyValue));
            }
            //最终价格
            double price2 = price.doubleValue();
            double goodsTotalPrice = price.add(discount).doubleValue();

            //可用优惠券数量
            int availableCouponLength = 0;
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            for (MarketCouponUser marketCouponUser : marketCouponUsers) {
                Integer couponId1 = marketCouponUser.getCouponId();
                MarketCoupon marketCoupon1 = marketCouponMapper.selectByPrimaryKey(couponId1);
                BigDecimal min1 = marketCoupon1.getMin();
                if (goodsTotalPrice >= min1.doubleValue()) {
                    availableCouponLength++;
                }
            }
            // 有无运费后的添加
            marketCouponUserMapper.deleteByPrimaryKey(userCouponId);
            if (price.doubleValue() < Integer.parseInt(keyValue2)) {
                checkoutVo = new WxCartCheckoutVo(grouponRulesId,price2,price2,
                        cartId,userCouponId,couponId,goodsTotalPrice,addressId,0,
                        discount.doubleValue(),availableCouponLength,Integer.parseInt(keyValue),marketAddress,marketCarts);
            }else if (price.doubleValue() >= Integer.parseInt(keyValue2)) {
                checkoutVo = new WxCartCheckoutVo(grouponRulesId, price2, price2,
                        cartId, userCouponId, couponId, goodsTotalPrice, addressId, 0,
                        discount.doubleValue(), availableCouponLength, 0, marketAddress, marketCarts);
            }

        } else if (userCouponId == -1 && couponId == -1) {
            //不使用优惠券

            //不满足满减运费
            if (price.doubleValue() < Integer.parseInt(keyValue2)) {
                price = new BigDecimal(price.doubleValue() + Integer.parseInt(keyValue));
            }
            //最终价格
            double price2 = price.doubleValue();
            double goodsTotalPrice = price.doubleValue();

            //可用优惠券数量
            int availableCouponLength = 0;
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            for (MarketCouponUser marketCouponUser : marketCouponUsers) {
                Integer couponId1 = marketCouponUser.getCouponId();
                MarketCoupon marketCoupon1 = marketCouponMapper.selectByPrimaryKey(couponId1);
                BigDecimal min1 = marketCoupon1.getMin();
                if (goodsTotalPrice >= min1.doubleValue()) {
                    availableCouponLength++;
                }
            }

            // 有无运费后的添加
            if (price.doubleValue() < Integer.parseInt(keyValue2)) {
                checkoutVo = new WxCartCheckoutVo(grouponRulesId,price2,price2,
                        cartId,userCouponId,couponId,goodsTotalPrice,addressId,0,
                        0,availableCouponLength,Integer.parseInt(keyValue),marketAddress,marketCarts);
            }else if (price.doubleValue() >= Integer.parseInt(keyValue2)) {
                checkoutVo = new WxCartCheckoutVo(grouponRulesId, price2, price2,
                        cartId, userCouponId, couponId, goodsTotalPrice, addressId, 0,
                        0, availableCouponLength, 0, marketAddress, marketCarts);
            }
        }

        return BaseRespVo.ok(checkoutVo);
    }

    @Override
    public BaseRespVo insertCart2(WxCartAddBo cartAddBo, Integer userId) {
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(cartAddBo.getGoodsId());
        String name = marketGoods.getName();
        String picUrl = marketGoods.getPicUrl();
        MarketGoodsProduct product = marketGoodsProductMapper.selectByPrimaryKey(cartAddBo.getProductId());
        BigDecimal price = product.getPrice();


        if (product.getNumber() < cartAddBo.getNumber()) {
            return BaseRespVo.invalidParameter("库存不足，请选择别的商品");
        }
        String[] specifications = product.getSpecifications();
        String goodsSn = String.valueOf(cartAddBo.getGoodsId());

        MarketCartExample example1 = new MarketCartExample();
        example1.createCriteria().andUserIdEqualTo(userId);
        List<MarketCart> marketCarts1 = marketCartMapper.selectByExample(example1);
        for (MarketCart marketCart : marketCarts1) {
            if (marketCart.getProductId() == cartAddBo.getProductId()) {
                Integer id = marketCart.getId();
                Short number = marketCart.getNumber();
                int num = number + cartAddBo.getNumber();
                MarketCart marketCart1 = new MarketCart();
                marketCart1.setId(id);
                marketCart1.setNumber((short) num);
                marketCartMapper.updateByPrimaryKeySelective(marketCart1);

                return BaseRespVo.ok(marketCart.getId());
            }
        }

        MarketCart marketCart = new MarketCart(null,userId,cartAddBo.getGoodsId(),
                goodsSn,name,cartAddBo.getProductId(),price,(short)cartAddBo.getNumber(),
                specifications,true,picUrl,new Date(),new Date(),false);

        marketCartMapper.insert(marketCart);

        return BaseRespVo.ok(marketCart.getId());
    }

    @Override
    public WxCartIndexVo deleteCart(WxCartDeleteBo deleteBo, Integer userId) {
        Integer[] productIds = deleteBo.getProductIds();

        for (Integer productId : productIds) {
            MarketCartExample example = new MarketCartExample();
            MarketCartExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andProductIdEqualTo(productId);

            marketCartMapper.deleteByExample(example);
        }

        return indexCart(userId);
    }

/*
    @Override
    public BaseRespVo selectCart2(Integer cartId, Integer addressId, Integer couponId, Integer userCouponId, Integer userId, Integer grouponRulesId) {
}
*/

    }

